var Token = require('../utils/jwtutil')
var models = require('../mysql/mysql');
var getDate = require('../utils/date')

/**
 * 注册接口
 * /user/register
 *  业务: 获取客户端提交的表单数据,存储到全局数组
 */
 const registerControl = async (req, res, next) => {
	// 接收参数
	// console.log(req.body);
	const imgurl = '' + req.file.filename
	// console.log(imgurl);
	const {userName,userPwd,nick} = req.body
	var sql = `insert into users(userName,userPwd,img_url,nick) values("${userName}","${userPwd}","${imgurl}","${nick}")`;  
	let data = await models(sql)

	if (data.length > 0) {
		// 登录成功
		res.send({
			code: 1,
			info: '注册成功',
		})
	} else {
		res.send({
			code: 1,
			info: '注册失败',
			msg: '1.检查文件是否上传\n 2.检查content-type是否正确\n 3.文件上传表单参数存储到FormDate中',
		})
	}
}

/**
 * 登录接口
 * /user/login
 *  业务: 获取表单数据，验证用户是否已经注册，
 *
 */
const loginControl = async (req, res, next) => {
	// 接收参数
	console.log(req.body);
	const {userName,userPwd} = req.body
	var sql = `select userName,userPwd,img_url,nick from users where userName='${userName}' and userPwd='${userPwd}'`;   // 表名，你自己数据库里有数据的表  
	let data = await models(sql)

	if (data.length > 0) {
		// 登录成功
		// 1. 生成token
		let token = Token.encrypt({userName, userPwd})
		//eyJhbpJ1c2VybmFZXVCJ9.eyJ1c2VybmFZwODMzODk0fQ.AQ29Lr-c4WOPfxTajKlAME
		res.send({
			code: 1,
			info: data[0],
			token
		})
	} else {
		res.send({
			code: -1,
			info: '账号不存在!',
		})
	}
}

/**
 * 用户列表接口
 * url: /users/list
 * method: get
 */
 const getUserList = async (req, res, next) => {
	// console.log('req.headers.authorization>>>',req.headers.authorization); // undefined 疑似要设置cookie
	// 接收参数
	const {pageSize=10,pageNum=1,name,shop,startPrice,endPrice} = req.query
	let namestr = `userName='${name}'`
	let startPricestr = `total_price>=${startPrice}`
	let endPricestr = `total_price<=${endPrice}`
	let wherestr = ``
	if(name){
		wherestr += `where`
		wherestr += ` ${name?namestr:''}`
	}
	console.log(wherestr);
	let count = await models(`select count(*) from users ${wherestr}`)
	let offset = (Number(pageNum)-1)*Number(pageSize)
	var sql = `select * from users ${wherestr} limit ${pageSize} offset ${offset}`; 
	let data = await models(sql)

	if (data.length > 0) {
		res.send({
			code: 1,
			info: {
				total:count[0]['count(*)'],
				list: data,
			},
		})
	} else {
		res.send({
			code: -1,
			info: '访客列表为空!',
		})
	}
}
module.exports = {loginControl,registerControl,getUserList}